package priv.conceit.study.leetcode.simple.official;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 编号349
 * 两个数组的交集
 * <a href="https://leetcode-cn.com/problems/intersection-of-two-arrays/">
 * <p>
 * 给定两个数组，编写一个函数来计算它们的交集。
 * <p>
 * 示例:
 * 输入: nums1 = [1,2,2,1], nums2 = [2,2]
 * 输出: [2]
 * <p>
 * 示例 2:
 * 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
 * 输出: [9,4]
 *
 * @author Conceit
 * @since 1.0.0, 2019/11/05
 */
public class IntersectionOfTwoArrays {

	public static void main(String[] args) {
		IntersectionOfTwoArrays intersectionOfTwoArrays = new IntersectionOfTwoArrays();
		int[] arr1 = {4, 9, 5};
		int[] arr2 = new int[5];
		arr2[0] = 9;
		arr2[1] = 4;
		arr2[2] = 9;
		arr2[3] = 8;
		arr2[3] = 4;
		int[] result = intersectionOfTwoArrays.intersection2(arr1, arr2);
		for (int x:result){
			System.out.println(x);
		}
	}

	/**
	 * 此方法占用过高
	 * @param nums1
	 * @param nums2
	 * @return
	 */
	public int[] intersection(int[] nums1, int[] nums2) {

		Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
		Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
		Set<Integer> set3 = new HashSet<>();

		set1.stream().forEach(x -> {
			if (set2.contains(x)) {

				set3.add(x);
			}
		});
		return set3.stream().mapToInt(Integer::intValue).toArray();
	}


	public int[] intersection2(int[] nums1, int[] nums2) {
		Set<Integer> list = new HashSet<>();

		for (int x : nums1) {
			if (contains(x, nums2)) {
				list.add(x);
			}
		}
		int [] output = new int[list.size()];
		int index=0;
		for (Integer set:list){
			output[index++]=set;
		}
		return output;


		//降低占用 废弃
		//return list.stream().mapToInt(Integer::intValue).toArray();
	}


	public boolean contains(int targer, int[] source) {
		for (int x : source) {
			if(targer == x){
				return true;
			}
		}
		return false;
	}


}
